<template>
  <div class="el-select orgset-treeselect">
    <treeselect
      v-bind="$attrs"
      :options="orgSets"
      :searchable="true"
      :clearable="true"
      :show-count="true"
      :flat="true"
      :multiple="false"
      :is-default-expanded="true"
      :normalizer="orgNormalizer"
      placeholder="选择组织机构"
      @select="orgSetSelect"
      v-on="$listeners"
    />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { getUserInfo } from '@/utils/auth'
import { getPrivOrgSetByUserAccount } from '@/api/user'
import { getOrgSetsByCpyCode } from '@/api/system/orgSet'

export default {
  components: { Treeselect },
  props: {
    hasPriv: {
      type: Boolean,
      default: true,
      required: false
    },
    valueField: {
      type: String,
      default: 'orgCode',
      required: false
    },
    curOrgId: {
      type: String,
      default: null,
      required: false
    }
  },
  data() {
    return {
      orgSets: []
    }
  },
  watch: {
    curOrgId() {
      // 获取所有组织机构
      getOrgSetsByCpyCode(this.curOrgId).then(res => {
        this.orgSets = res.data
      })
    }
  },
  created() {
  },
  mounted() {
    if (this.hasPriv) {
      const userInfo = getUserInfo()
      const cpycode = userInfo.cpyCode
      // 获取当前用户有权限的机构
      getPrivOrgSetByUserAccount(cpycode).then(res => {
        this.orgSets = res.data
      })
    } else {
      getOrgSetsByCpyCode(this.curOrgId).then(res => {
        this.orgSets = res.data
      })
    }
  },
  methods: {
    orgNormalizer(node) {
      return {
        id: node[this.valueField],
        label: node.orgName
      }
    },
    orgSetSelect(node, instanceId) {
    }
  }
}
</script>
<style scoped>
  .orgset-treeselect{
    padding-left: 3px;
    height:25px;
  }
</style>
